<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <div v-if="switchFlag">
        <Row :gutter="16" class="query-form2">
          <i-col span="8">
            <FormItem label="二级集团：" prop="twoLevelOrgId">
              <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="被检查单位：" prop="inspectedCompanyName">
              <company-select v-model="form1.inspectedCompanyName"></company-select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="日期：" prop="inspectionDate">
              <DatePicker v-model="form1.inspectionDate" type="date" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择检查日期"></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="被检查人员：" prop="inspectedPeople">
              <Input class="query-form-el" type="text" v-model="form1.inspectedPeople"></Input>
            </FormItem>
          </i-col>
          <Col span="16">
            <div style="float: right;">
              <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
              <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
            </div>
          </Col>
        </Row>
      </div>
      <div v-else>
        <Row :gutter="16" class="query-form2">
          <i-col span="8">
            <FormItem label="二级集团：" prop="twoLevelOrgId">
              <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="被检查单位：" prop="inspectedCompanyName">
              <company-select v-model="form1.inspectedCompanyName"></company-select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
              <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
            </div>
          </i-col>
        </Row>
      </div>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <download-button :api="exportUrl" :queryForm="form1" :exportFormBefore="exportFormBefore" />
          <!-- <Button type="primary" class="ivu-btn-add"   icon="md-cloud-download"  @click="exportFormSubmit">导出</Button> -->
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows' @on-sort-change="querySort"
           border :columns="columns1" :data="dataTable">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="title" :transfer=false v-model="model1" :width=800>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="检查日期：" prop="inspectionDate">
                  <DatePicker v-model="form1datacopy.inspectionDate" type="date"
                              style="width: 100%" format="yyyy-MM-dd"
                              placeholder="请选择检查时间"></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="录入人：" prop="inputUserName">
                  <Input type="text" v-model="form1datacopy.inputUserName"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="检查组成员：" prop="inspectionPerson">
                  <Input tyype="textarea" v-model="form1datacopy.inspectionPerson" type="text"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="被检查单位：" prop="inspectedCompanyName">
                  <Input class="query-form-el" type="text" v-model="form1datacopy.inspectedCompanyName"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="检查区域：" prop="inspectedArea">
                  <Input type="text" v-model="form1datacopy.inspectedArea"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="检查部位：" prop="inspectedCheckPoint">
                  <Input type="text" v-model="form1datacopy.inspectedCheckPoint"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="被检查单位人员：" prop="inspectedPerson">
                  <Input tyype="textarea" v-model="form1datacopy.inspectedPerson"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="检查内容和工作要求：" prop="inspectedContent">
                  <Input v-model="form1datacopy.inspectedContent" type="textarea" :rows="5"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="发现的主要问题及整改要求：" prop="inspectedProblem" :rows="5">
                  <Input v-model="form1datacopy.inspectedProblem" type="textarea"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="附件：" prop="zuopin">
                  <Upload
                      multiple
                      ref="upload"
                      type="drag"
                      name="files"
                      :show-upload-list="false"
                      :before-upload="beforeUpload"
                      :action="fileUrl">
                    <div style="padding: 20px 0">
                      <Icon type="ios-cloud-upload" size="52" style="color: #F27874"></Icon>
                      <p><span style="color: red">*</span>点击将文件拖拽到这里上传</p>
                    </div>
                  </Upload>
                  <div v-for="(item, index) in fileList" :key="index">
                    <a>{{item.name}}</a>
                    <Button type="text" icon="md-trash" @click="removeFile(item.keyID)"  style="margin-left: 10px;margin-bottom: 3px"/>
                    <Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>
                    <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                  <div v-for="(item, index) in modifyFile" :key="index">
                    <a @click.prevent="downloadFile(item,index)">{{item.fileName}}</a>
                    <Button type="text" icon="md-trash" @click.native="removeFile2(item)"  style="margin-left: 10px;margin-bottom: 3px"/>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="submit('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="安全监督检查记录详情" class="modal-view-detail" :transfer=false v-model="model2" :width=800>
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="200">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="日期：" prop="inspectionDate">
                  {{showdata.inspectionDateStr}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="录入人：" prop="inputUserName">
                  {{showdata.inputUserName}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="检查组成员：" prop="inspectionPerson">
                  {{showdata.inspectionPerson}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="被检查单位：" prop="inspectedCompanyName">
                  {{showdata.inspectedCompanyName}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="检查区域：" prop="inspectedArea">
                  {{showdata.inspectedArea}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="检查部位：" prop="inspectedCheckPoint">
                  {{showdata.inspectedCheckPoint}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="被检查单位人员：" prop="inspectedPerson">
                  {{showdata.inspectedPerson}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="检查内容和工作要求：" prop="inspectedContent">
                  {{showdata.inspectedContent}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="发现的主要问题及整改要求：" prop="inspectedProblem">
                  {{showdata.inspectedProblem}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="附件：" prop="orgName">
                  <div v-for="(item, index) in modifyFile" :key="index">
                    <a @click.prevent="downloadFile(item,index)">{{item.fileName}}</a>
                    <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import cascaderDom from "../../../components/cascader-dom.vue"
import {
  sessionStorage
} from '../../../common/cacheUtils.js';
import {
  Api
} from '../../../api/index.js'

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      loading2: false,
      model3:false,
      buttonLoading: false,
      loading: false,
      title: "",
      saveMod: false,
      switchFlag: false,
      form1: {},
      setCurrentName: {},
      fileList: [],
      modifyFile: [],
      filePercent:[],
      filePercentVisible:[],
      uploadListVisible:[],
      uploadListPercent:[],
      fileUrl: '',
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      currentUserId: sessionStorage('userId').getObject('userId').userId,
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 150,
          title: '被检查单位',
          align: 'center',
          key: 'inspectedCompanyName',
        },
        {
          minWidth: 300,
          title: '检查区域',
          align: 'center',
          key: 'inspectedArea',
        },
        {
          minWidth: 150,
          title: '检查部位',
          align: 'center',
          key: 'inspectedCheckPoint',
        },
        {
          minWidth: 150,
          title: '检查日期',
          align: 'center',
          key: 'inspectionDate',
          sortable: 'custom',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.inspectionDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '录入人员',
          align: 'center',
          key: 'inputUserName'
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let flag =(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId
                || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined ||
                (this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined &&
                    params.row.orgCode && params.row.orgCode.indexOf(this.currentUser.companyCode)!=-1))
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {style: {
                    fontSize: '14px',
                    color:flag?'':'#c5c8ce',
                    pointerEvents:flag?'':'none'
                  },
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'red':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '删除'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.exportExecl(params);
                  }
                }
              }, '导出'),
            ]);
          }
        }
      ],
      ruleCustom: {
        inspectionCompanyName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        inspectedArea: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        inspectedCheckPoint: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        inspectionPerson: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        inspectedPerson: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        inspectDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      form1datacopy: {
        fillInTime: [],
        execlSheet: "{}"
      },
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      add: false,
      tableHeight: 10,
      exportUrl: Api.exportSafetyRecordAll
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
  },
  methods: {
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 35;
      } else {
        this.tableHeight = this.tableHeight + 35;
      }
    },
    setOrgId(data) {
      this.form1datacopy.inspectedCompanyId = data[data.length - 1];
    },
    setOrgName(data){
      this.form1datacopy.inspectedCompanyName = data;
    },
    selectThemeList() {
      let data = {
        currentPage: 1,
        size: 100
      }
    },
    beforeUpload (file) {
      let keyID = Math.random().toString().substr(2);
      file['keyID'] = keyID;
      this.filePercent[this.fileList.length]=0;
      this.filePercentVisible[this.fileList.length]=false;
      this.fileList.push(file);
      return false;
    },
    async handUpload(){
      var index = 0;
      var length = this.fileList.length;
      var _this = this;
      for(var i=0;i<this.fileList.length;i++){
        if(this.fileList[i].id != undefined){
          _this.$set(_this.filePercentVisible,index,true);
           _this.$set(_this.filePercent,index, 100);
          index++
          if (res.data.result == "success" && index == length) {
            this.$Message.info("文件上传成功")
          }
        }else {
          let formData = new FormData();
          var config = {
            progress: function (e) {
              _this.$set(_this.filePercentVisible, index, true);
              if (e.lengthComputable) {
                _this.$set(_this.filePercent, index, 100 * (e.loaded / e.total));
              }
            }
          }
          formData.append("files", this.fileList[i]); // 文件对象
          await this.$http.post(this.fileUrl, formData, config).then((res) => {
            index++
            if (res.data.result == "success" && index == length) {
              this.$Message.info("文件上传成功")
            }
          })
        }
      }
    },
    downloadFile(file,index){
      let url = Api.interestedPartiesUserFile + '/file/' + file.id;
      this.uploadListVisible[index] = true;
      var _this = this;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress:function(e){
          _this.$set(_this.uploadListPercent,index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      }, function(res){
        this.$Loading.error();
      })
    },
    removeFile(keyID){
      this.fileList = this.fileList.filter(item => {
        return item.keyID != keyID
      })
    },
    removeFile2(file){
      this.$http.delete(Api.uploadMongoFile + "/" + file.id).then((res) => {
        this.modifyFile.splice(this.modifyFile.indexOf(file), 1);
      }).catch(e => {
        this.$Message.error("附件删除失败");
      });
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    cancel(){
      this.form1 = {};
      this.query1();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    showData(data, flag) {
      this.buttonLoading = false;
      if (flag == 1) {
        //查看页面
        this.modifyFile = [];
        this.showdata = data.row;
        if (this.showdata.inspectionDate != null) {
          this.showdata.inspectionDateStr = this.formatDate(new Date(this.showdata.inspectionDate), 'yyyy-MM-dd');
        }
        this.fileUrl = Api.uploadPTWFiles  + '/' + this.showdata.safetyRecordId + '/files/file'
        this.model2 = true;
      } else {
        this.title = "安全监督检查修改";
        this.saveMod = false;
        this.add = false;
        this.fileList.splice(0,this.fileList.length)
        this.modifyFile.splice(0,this.modifyFile.length)
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.fileUrl = Api.uploadPTWFiles  + '/' + this.form1datacopy.safetyRecordId + '/files/file'
        this.model1 = true;
      }
      this.$http.get(this.fileUrl,{
        params: {},
      }).then((res) => {
        var index = 0;
        res.data.data.map((i) =>{
          this.modifyFile.push(i);
          this.uploadListPercent[index]=0;
          this.uploadListVisible[index] = false;
          index++;
        })
      })
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(params) {
      let url = Api.deleteSafetyRecord;
      this.$http.delete(url + '/' + params.row.safetyRecordId).then((res) => {
        if(res.data.status == 200) {
          this.$Message.success('删除成功');
          this.query()
        }else{
          this.$Message.error("删除失败")
        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    exportFormBefore(data) {
      data.createCompanyName = sessionStorage('userId').getObject('userId').companyName
      if(data.inspectionDate != undefined && data.inspectionDate != '') {
        data.inspectionDate = this.formatDate(new Date(data.inspectionDate), 'yyyy-MM-dd');
      }
    },
    query1(){
      this.pagedata.currentPage = 1;
      this.query()
    },
    query() {
      this.loading = true;
      let companyName = sessionStorage('userId').getObject('userId').companyName
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        createCompanyName: companyName
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      if(data.inspectionDate != undefined && data.inspectionDate != '') {
        data.inspectionDate = this.formatDate(new Date(data.inspectionDate), 'yyyy-MM-dd');
      }
      let url = Api.safetyRecordList;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.loading = false;
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {}
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    async submit(name) {
      this.$refs[name].validate(async(valid) => {
        if (valid) {
          this.saveMod = true;
          this.buttonLoading = true;
          await this.handUpload();
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').companyId;
          this.form1datacopy.activityType = this.$route.query.type;
          this.form1datacopy.inspectionDate = this.formatDate(new Date(this.form1datacopy.inspectionDate), 'yyyy-MM-dd');
          if (this.add) {
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.$http.post(Api.saveSafetyRecord, this.form1datacopy).then((res) => {
              if(res.data.status == 200) {
                this.$Message.success("保存成功")
                this.model1 = false;
                this.saveMod = false;
                this.query();
                this.buttonLoading = false;
              }else{
                this.$Message.error("保存失败");
                this.buttonLoading = false;
              }
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateSafetyRecord, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.saveMod = false;
              this.model1 = false;
              this.query();
              this.buttonLoading = false;
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    addInfo() {
      this.title = "安全监督检查新增";
      this.saveMod = false;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let userName = sessionStorage('userId').getObject('userId').userName;
      this.form1datacopy = {
        safetyRecordId:this.uuid(),
        inputUserId:userId,
        inputUserName:userName,
      };
      this.fileUrl = Api.uploadPTWFiles  + '/' + this.form1datacopy.safetyRecordId + '/files/file'
      this.add = true;
      this.model1 = true;
      this.fileList.splice(0,this.fileList.length)
      this.modifyFile.splice(0,this.modifyFile.length)
    },
    exportExecl(params){
      this.exportLoading = true;
      this.$http.get(Api.exportSafetyRecord + '/' + params.row.safetyRecordId, {responseType: 'blob' }).then(res => {
        this.exportLoading = false;
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = params.row.inspectedCompanyName +  "安全监督检查记录.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      }).catch(e => {
        this.exportLoading = false;
        this.$Message.error("导出失败")
      })
    },
    exportFormSubmit() {
      this.$Spin.show({
            render: (h) => {
                return h('div', [
                    h('Icon', {
                        'class': 'demo-spin-icon-load',
                        props: {
                            type: 'ios-loading',
                            size: 18
                        }
                    }),
                    h('div', 'Loading')
                ])
            }
        });
        let data = {}
        for (let key in this.form1) {
            let value = this.form1[key]
            if (value) {
                data[key] = value
            }
        }
        this.$http.get(Api.exportSafetyRecordAll, {
            params: data,
            responseType: 'blob'
        }).then(res => {
            this.$Spin.hide();
            const aLink = document.createElement("a");
            aLink.target = '_blank'
            let blob = new Blob([res.data], {
                type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
            });
            aLink.href = URL.createObjectURL(blob)
            // if (!fileName) {
            //     let dis= res.headers.map['content-disposition']
            //     fileName=dis.toString().split('attachment;filename=')[1]
            //     fileName = decodeURIComponent(decodeURI(fileName))
            // }
            aLink.download = "监督检查记录.xlsx" //标题
            aLink.click()
            document.body.appendChild(aLink)
        }).catch((r) => {
            console.error(r)
            this.$Spin.hide();
            this.$Message.error('下载文件出现错误，请联系管理员！')
        })
    },
    importExecl(){

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for(let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      let uuid = s.join("");
      return uuid
    },
    querySort({column, key, order}){
      this.form1.key = key;
      this.form1.order = order;
      this.query1();
    }
  }
}
</script>
<style scoped>
@import '../../../index.css';

.execlClass{
  width:100%;
  height:300px
}


</style>
